import {addFeedback} from "../../api/api";
import Util from '../../utils/util.js';

const app = getApp();
Page({

  /**
   * 页面的初始数据
   */
  data: {
    fields: {
      type: {
        title: '类型',
        type: "radio",
        options: ['建议', '投诉'],
        default_val: 0,
      },

      order_id: {
        title: '订单号',
        placeholder: "请填写相关订单号，以便我们更好地为您提供",
        default_val: "",
        relate_key: 'type',
        relate_val: 1,
      },

      content: {
        title: '问题描述',
        type: "textarea",
        placeholder: "请填写15字以上描述，以便我们更好地为您提供帮助~",
        max: 500,
        required: true
      },
      feedback_img: {
        title: '上传图片',
        subtitle: '最多3张',
        type: "mutilImage",
        class: "margin10-b",
        max: 3
      },
      contact_phone: {
        title: '联系方式',
        required: true,
        class: "margin10-b",
        placeholder: "请填写您的手机号码",
        type: "input",
        max: 3
      },
    },
    selectIndex: "",
    btnActive: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this;

    Util.chekWxLogin().then(res => {
      wx.hideLoading()
      that.setData({
        userInfo: res.userInfo,
      })
      that.onLoadTabbar()
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },


  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  formSubmit(e) {
    const that = this;
    const form_data = e.detail.value;
    const fields = that.data.fields;
    let photo_ids = [];

    if (!Util.isEmpty(fields['feedback_img'].values)) {
      fields['feedback_img'].values.forEach(e1 => {
        photo_ids.push(e1.id)
      })
    }
    form_data['picture_ids'] = photo_ids

    let msg = "";
    for (const k in fields) {
      if (fields[k].isShow) continue;

      if (fields[k].required && !form_data[k]) {
        fields[k].focus = true;
        msg = fields[k].title + "必填";
        this.setData({
          fields: fields
        })
        break;
      }
    }

    if (msg) {
      this.setData({btnActive: true})
      return Util.Tips({title: msg, hideMask: true});
    }

    if (!this.data.btnActive) {
      return Util.Tips({title: "不要重复提交", hideMask: true});
    }
    this.setData({btnActive: false})
    wx.showLoading({
      title: '正在提交..',
    })
    addFeedback(form_data).then(res => {
      this.setData({btnActive: true})
      return Util.Tips({title: form_data.type == 1 ? '投诉成功' : res.msg, icon: "success", endtime: 1500}, {tab: 3})
    }).catch(errmsg => {
      this.setData({btnActive: true})
      return Util.Tips({title: errmsg});
    });

  },

  radioChange(e) {
    const fields = this.data.fields;
    if (!e.target.id) {
      return;
    }
    fields[e.target.id].default_val = e.detail.value;
    this.setData({fields})
  },

  inputName(e) {
    const that = this, fields = this.data.fields;
    const id = e.currentTarget.id;
    fields[id].default_val = e.detail.value;
    this.setData({fields: fields});
  },

  onChooseMutiImage: function (e) {

    const that = this,
      key = e.currentTarget.dataset.key,
      fields = that.data.fields,
      max = e.currentTarget.dataset.max,
      images = fields[key].values || [];

    if (max && images >= max) {
      return app.Tips({title: "最多上传" + max + "张"});
    }

    wx.chooseImage({
      success(res) {
        const tempFilePaths = res.tempFilePaths;
        if (max && images.length + tempFilePaths.length > max) {
          return app.Tips({title: "最多上传" + max + "张", hideMask: true});
        }

        const url = `${app.globalData.url}/api/file/upload`; // 仅为示例，非真实的接口地址
        wx.showLoading({
          title: '正在上传..',
        })
        for (let i = 0; i < tempFilePaths.length; i++) {
          wx.uploadFile({
            method: "POST",
            url: url,
            filePath: tempFilePaths[i],
            name: 'fileData',
            header: {
              token: wx.getStorageSync("cookie_token"),
            },
            formData: {},
            success(res) {
              const data = JSON.parse(res.data) || {};
              images.push({path: data.data.path, id: data.data.id});
              fields[key].values = images;
              that.setData({
                fields: fields
              });
              wx.hideLoading();
            },
            fail(res) {
              wx.hideLoading();
            }
          });
        }
      }
    });
  },

  removePic(e) {
    const that = this;
    const k = e.currentTarget.dataset.k,
      fk = e.currentTarget.dataset.fk,
      fields = that.data.fields;

    fields[fk].values.splice(k, 1);
    that.setData({
      fields: fields
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  onLoadTabbar: function () {//底部tabbar返回数据
    const that = this

    Util.checkIphone().then(res => {//检查是否是iphone x/11等
      that.setData({isIphoneX: res})
      wx.createSelectorQuery().in(that).select('#weui-footer')
        .boundingClientRect(function (rect) {
          if (!rect) return false;
          that.setData({
            bottom: parseInt(rect.height || 0) + 15
          })
        }).exec()
    });

  },

  onReachBottom: function () {
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})